package one.to.one.foreignkey;

import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import utils.HibernateUtils;

public class HibernateTest {

	private Session session;

	@Before
	public void before() {
		session = HibernateUtils.getSession();
		session.beginTransaction();
	}
	
	@Test
	public void testGet2(){
		//当查询没有关联主键的哪一方的时候，使用左外联结查询出所有结果
		Manager manager = session.get(Manager.class, 3);
		
		System.out.println(manager.getClass());
		System.out.println(manager.getMgrName());
		System.out.println(manager.getDept().getDeptName());
	}

	@Test
	public void testGet() {
		// 1. 默认情况下对关联属性使用懒加载
		Department dept = session.get(Department.class, 3);

		System.out.println(dept.getDeptName());
		/* System.out.println(dept.getMgr().getMgrName()); */

		//懒加载问题
		/*session.close();
		Manager mgr = dept.getMgr();
		System.out.println(mgr.getClass());
		System.out.println(mgr.getMgrName());*/

		// 3. 查询 Manager 对象的连接条件应该是 dept.manager_id = mgr.manager_id
		// 而不应该是 dept.dept_id = mgr.manager_id
		Manager mgr = dept.getMgr();
		System.out.println(mgr.getMgrName());

	}

	@Test
	public void testSave() {
		Department dept = new Department();

		dept.setDeptName("DD-BB");

		Manager manager = new Manager();
		Manager manager2 = new Manager();

		manager.setMgrName("DGW!");
		// 设定关联关系
		dept.setMgr(manager);
		manager2.setDept(dept);
		// 保存操作
		// 建议先保存没有外键列的那个对象. 这样会减少 UPDATE 语句
		session.save(manager);
		session.save(dept);

	}

	@After
	public void after() {
		session.getTransaction().commit();
		session.close();
	}

}
